!**********************************************************
! this mod contains the grd file
!**********************************************************
! grd_mn_sub(infile,m,n) 
! grd_region_sub(infile,xmin,xmax,ymin,ymax,zmin,zmax)
! grd_dat_sub(infile,m,n,dat)
! grd_out_sub(outfile,m,n,dat,xmin,xmax,ymin,ymax)
!**********************************************************
!include 'datio.f90'

subroutine open_or_not(nut)
integer   nut
integer ext
nut =11
do 
        inquire(nut,exist=ext)
        if(ext.ne.0) exit
        nut=nut+1
enddo
end subroutine
!************************************************
!input m,n from infile
subroutine grd_mn_sub(infile,m,n)
character*(*) infile
integer m,n
integer nut
integer sta
call open_or_not(nut)
open(nut,file=infile,iostat=sta)
if(sta.ge.0)then
    read(nut,*)
    read(nut,*) n,m
endif
close(nut)
end subroutine
!
subroutine grd_region_sub(infile,xmin,xmax,ymin,ymax,zmin,zmax)
character(*) infile
real xmin,xmax,ymin,ymax,zmin,zmax
integer nut
integer sta
call open_or_not(nut)
open(nut,file=infile,iostat=sta)
if(sta.ge.0)then
    read(nut,*)
    read(nut,*) n,m
    read(nut,*) xmin,xmax
    read(nut,*) ymin,ymax
    read(nut,*) zmin,zmax
endif
close(nut)

end subroutine
!
subroutine grd_dat_sub(infile,m,n,dat)
character(*) infile
integer m,n
integer nut
integer sta
real dat(m,n)
call open_or_not(nut)
open(nut,file=infile,iostat=sta)
if(sta.ge.0)then
    read(nut,*)
    read(nut,*)
    read(nut,*)
    read(nut,*)
    read(nut,*) 
do i=1,m
    read(nut,*) (dat(i,j),j=1,n)
enddo
endif
close(nut)

end subroutine
!
subroutine grd_out_sub(outfile,m,n,dat,xmin,xmax,ymin,ymax)
character(*) outfile
integer m,n
real xmin,xmax,ymin,ymax,zmin,zmax
real dat(m,n)
integer sta
zmin=dat(1,1)
zmax=zmin
do i=1,m
do j=1,n
  zmin=min(zmin,dat(i,j))
  zmax=max(zmax,dat(i,j))
enddo
enddo
call open_or_not(nut)
open(nut,file=outfile,iostat=sta)
write(nut,'(A)')'DSAA'
WRITE(nut,*)n,m
write(nut,*)xmin,xmax
write(nut,*)ymin,ymax
write(nut,*)zmin,zmax
do i=1,m
    write(nut,*) (dat(i,j),j=1,n)
enddo
close(nut)
end subroutine
!********** this is the end of grd.f90 *******************************
